<?php namespace App\Services;
use App\Models\User;
use Sentinel;
use App\Exceptions\DataBaseException;
use App\Exceptions\ValidateParameterException;
use App\Models\RoleUser;
use DB;

class UserService{
	public function getUsers(){
		return Sentinel::getUserRepository()->with(['roles'])->get();
	}

	public function getUser($id){
		return User::with(['roles'])->find($id);
	}

	public function addUser($data,$roleId){
		$role = Sentinel::findRoleById($roleId);
    	
    	$user = Sentinel::registerAndActivate($data);

    	$role->users()->attach($user);
	}

	public function updateUser($id,$data,$roleId){
		if($data['password'] == ''){
			$data = array_except($data,['password']);
		}

		DB::transaction(function() use($id,$data,$roleId){
			$user = Sentinel::findById($id);

			$updateRoleUser = [
				'role_id' => $roleId
			];

			$roleUser = RoleUser::find($id);

			$roleUser->update($updateRoleUser);

			Sentinel::update($user, $data);
		});
	}

	public function deleteUser($id){
		$user = Sentinel::findById($id);

		$user->delete();
	}

	public function updateOneSelf($data){
		$updateData = [
			'last_name' => $data['last_name'],
			'first_name' => $data['first_name']
		];

		if(isset($data['password']) && $data['password'] != ''){
			if(isset($data['confirmPassword']) && $data['confirmPassword'] != ''){
				if($data['password'] == $data['confirmPassword']){
					$updateData['password'] = $data['password'];
				}
				else{
					throw new ValidateParameterException("确认密码与密码不一致");
				}
			}
			else{
				throw new ValidateParameterException("确认密码不能为空");
			}
		}
		
		$user = Sentinel::getUser();

		Sentinel::update($user,$updateData);
	}
}